<template>
    <div class="default-main ba-table-box">
        <el-alert
            class="ba-table-alert group-super-alert"
            v-if="!adminInfo.super"
            :title="t('auth.group.Manage subordinate role groups here')"
            type="info"
            show-icon
        />
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 'unfold',-->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('auth.group.GroupName') })"
        />

        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" :pagination="false" />

        <!-- 表单 -->
        <PopupForm ref="formRef" />
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import { useAdminInfo } from '/@/stores/adminInfo'
import baTableClass from '/@/utils/baTable'
import { getArrayKey } from '/@/utils/common'
import { uuid } from '/@/utils/random'
import createAxios from '/@/utils/axios'
import { useConfig } from '/@/stores/config'

defineOptions({
    name: 'auth/group',
})

const formRef = ref()
const tableRef = ref()
const { t } = useI18n()
const adminInfo = useAdminInfo()

const baTable: baTableClass = new baTableClass(
    new baTableApi('/backend/admin-role/'),
    {
        expandAll: true,
        dblClickNotEditColumn: [undefined],
        column: [
            { type: 'selection', align: 'center' },
            { label: t('auth.group.Group name'), prop: 'name', align: 'left', width: '200' },
            { label: t('auth.group.jurisdiction'), prop: 'auth_name', align: 'center', show: useConfig().lang.defaultLang == 'zh-cn' },
            { label: t('auth.group.jurisdiction'), prop: 'en_auth_name', align: 'center', show: useConfig().lang.defaultLang == 'en' },
            {
                label: t('State'),
                prop: 'status',
                align: 'center',
                render: 'tag',
                custom: { '0': 'danger', '1': 'success' },
                replaceValue: { '0': t('Disable'), '1': t('Enable') },
            },
            { label: t('Update time'), prop: 'mtime', align: 'center', width: '160', render: 'datetime' },
            { label: t('Create time'), prop: 'ctime', align: 'center', width: '160', render: 'datetime' },
            { label: t('Operate'), align: 'center', width: '130', render: 'buttons', buttons: defaultOptButtons(['edit', 'delete']) },
        ],
    },
    {
        defaultItems: {
            status: '1',
        },
    },
    {
        // 提交前
        onSubmit: ({ formEl, operate, items }) => {
            let submitCallback = () => {
                baTable.form.submitLoading = true
                baTable.api
                    .postData(operate, {
                        ...items,
                        //rules: formRef.value.getCheckeds(),
                    })
                    .then((res) => {
                        baTable.onTableHeaderAction('refresh', {})
                        baTable.form.submitLoading = false
                        baTable.form.operateIds?.shift()
                        if (baTable.form.operateIds!.length > 0) {
                            baTable.toggleForm('Edit', baTable.form.operateIds)
                        } else {
                            baTable.toggleForm()
                        }
                        baTable.runAfter('onSubmit', { res })
                    })
                    .catch(() => {
                        baTable.form.submitLoading = false
                    })
            }

            if (formEl) {
                baTable.form.ref = formEl
                formEl.validate((valid) => {
                    if (valid) {
                        submitCallback()
                    }
                })
            } else {
                submitCallback()
            }
            return false
        },
        // 双击编辑前
        onTableDblclick: ({ row }) => {
            return baTable.table.extend!.adminGroup.indexOf(row.id) === -1
        },
    },
    {
        getLists: ({ res }) => {
            console.log('==>页面获取列表返回的数据', res.data.list)
            baTable.table.extend!.adminGroup = res.data.list
            let buttonsKey = getArrayKey(baTable.table.column, 'render', 'buttons')
            baTable.table.column[buttonsKey].buttons!.forEach((value: OptButton) => {
                value.display = (row) => {
                    return res.data.list.indexOf(row.id) === -1
                }
            })
        },
        // 切换表单后
        toggleForm({ operate }) {
            if (operate == 'Show') {
                menuRuleTreeUpdate()
            }
            if (operate == 'Edit') {
                menuRuleTreeUpdate()
            }
            if (operate == 'Add') {
                menuRuleTreeUpdate()
            }
        },
        // 编辑请求完成后
        requestEdit() {
            menuRuleTreeUpdate()
        },
        // 编辑请求完成后
        requestShow() {
            menuRuleTreeUpdate()
        },
    }
)

const menuRuleTreeUpdate = () => {
    // 获取所有的菜单
    createAxios({
        url: '/backend/admin-role/menu',
        method: 'get',
    }).then((res) => {
        //baTable.form.extend!.menuRules = res.data
        console.log('弹出修改前获取栏目', res.data)
        console.log('弹出修改前', baTable.form.items)
        console.log(baTable.form.items!.auth)

        // 菜单展示
        const locale = useConfig().lang.defaultLang
        let menu: any = {}
        for (const key in res.data) {
            if (locale == 'zh-cn') {
                menu[res.data[key].role] = res.data[key].name
            } else {
                menu[res.data[key].role] = res.data[key].en_name
            }
        }
        console.log('弹出修改前栏目整理', menu)
        baTable.form.extend!.menuRules = menu

        // 选中的
        if (baTable.form.items!.auth && baTable.form.items!.auth.length) {
            if (baTable.form.items!.auth.includes('*')) {
                let checked: any = []
                let values: any = []
                for (const key in menu) {
                    checked.push(menu[key].role)
                    values[menu[key].role] = true
                }
                baTable.form.extend!.defaultCheckedKeys = values
                baTable.form.items!.auth = checked
            } else {
                baTable.form.extend!.defaultCheckedKeys = baTable.form.items!.auth
                baTable.form.items!.auth = baTable.form.items!.auth
            }
        } else {
            baTable.form.extend!.auth = []
            baTable.form.items!.auth = []
        }

        console.log('制作的弹出权限信息：选中的', baTable.form.extend!.defaultCheckedKeys)
        baTable.form.extend!.treeKey = uuid()
    })
}

// 以前树状菜单
const _menuRuleTreeUpdate = () => {
    // 获取所有的菜单
    createAxios({
        url: '/backend/admin-role/menu',
        method: 'get',
    }).then((res) => {
        baTable.form.extend!.menuRules = res.data
        console.log('弹出修改前', baTable.form.items)
        console.log(baTable.form.items!.rules)

        if (baTable.form.items!.rules && baTable.form.items!.rules.length) {
            if (baTable.form.items!.rules.includes('*')) {
                let arr: number[] = []
                for (const key in baTable.form.extend!.menuRules) {
                    arr.push(baTable.form.extend!.menuRules[key].id)
                }
                baTable.form.extend!.defaultCheckedKeys = arr
            } else {
                baTable.form.extend!.defaultCheckedKeys = baTable.form.items!.rules
            }
        } else {
            baTable.form.extend!.defaultCheckedKeys = []
        }

        console.log('制作的弹出权限信息', baTable.form.extend!.defaultCheckedKeys)
        baTable.form.extend!.treeKey = uuid()
    })
}

provide('baTable', baTable)

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getLists()
})
</script>

<style scoped lang="scss">
.group-super-alert {
    margin-bottom: 10px;
}
</style>
